<template>
  <div>
    <div class="top">
      <div class="search">
        <el-form :inline="true" :model="formInline">
          <el-form-item :label="t('productId')" class="status">
            <el-select
              v-model="formInline.product_id"
              :placeholder="t('pleaseSelect')"
              clearable
            >
              <el-option
                v-for="product in productList"
                :key="product.product_id"
                :label="product.product_name"
                :value="product.product_id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery()">{{ t('query') }}</el-button>
          </el-form-item>
          <!--          <el-form-item>
                      <el-button type="primary" @click="addProduct()"
                      >新增配置方案
                      </el-button>
                    </el-form-item>-->
        </el-form>
      </div>
    </div>
    <el-table class="table_content" v-loading="loadingData" :data="paginatedData" :border="true">
      <el-table-column prop="product_id" :label="t('productId')"></el-table-column>
      <el-table-column prop="apply_limit" :label="t('dayLimit')"></el-table-column>
      <el-table-column :label="t('isOpen')">
        <template #default="{ row }">
          <el-tag v-if="row.apply_switch === 1" type="success">{{ t('hasOpen') }}</el-tag>
          <el-tag v-else type="info">{{ t('hasClose') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="apply_start_time" :label="t('dayStartApplyTime')"></el-table-column>
      <el-table-column prop="apply_end_time" :label="t('dayEndApplyTime')"></el-table-column>
      <el-table-column
        prop="create_time"
        :label="t('createTime')"
      ></el-table-column>
      <el-table-column
        prop="update_time"
        :label="t('updateTime')"
      ></el-table-column>
      <el-table-column :label="t('op')">
        <template #default="{ row }">
          <el-button type="danger" size="small" @click="handleEnable(row,0)" v-if="row.apply_switch === 1">{{ t('close')
            }}
          </el-button>
          <el-button type="success" size="small" @click="handleEnable(row,1)" v-else>{{ t('open') }}</el-button>
          <el-button type="primary" size="small" @click="handleEdit(row)"
          >{{ t('edit') }}
          </el-button
          >
          <!--          <el-button type="danger" size="small" @click="handleDelete(row)"
                    >删除
                    </el-button
                    >-->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="configList.length"
    >
    </el-pagination>
    <!--  启用停用对话框  -->
    <el-dialog
      v-model="centerDialogVisible"
      :title="t('tip')"
      width="500"
      align-center
    >
      <span>{{ t('sureTo') }}{{ enableStatusDesc }}{{ t('thisConfig') }}</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">{{ t('cancel') }}</el-button>
          <el-button type="primary" @click="doChangeProductStatus()">
            {{ t('confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!--  编辑弹窗  -->
    <!-- 编辑配置的弹窗 -->
    <el-dialog v-model="editDialogVisible" :title="t('edit')">
      <el-form :model="currentRow" label-width="120px">
        <el-form-item :label="t('applyStartTime')">
          <el-time-picker v-model="currentRow.apply_start_time" format="HH:mm" value-format="HH:mm"
                          :placeholder="t('selectTime')"></el-time-picker>
        </el-form-item>
        <el-form-item :label="t('applyEndTime')">
          <el-time-picker v-model="currentRow.apply_end_time" format="HH:mm" value-format="HH:mm"
                          :placeholder="t('selectTime')"></el-time-picker>
        </el-form-item>
        <el-form-item :label="t('applyLimit')">
          <el-input-number v-model="currentRow.apply_limit" :min="0"></el-input-number>
        </el-form-item>
        <!--        <el-form-item label="状态">
                  <el-switch v-model="currentRow.apply_switch" :active-value="1" :inactive-value="0"></el-switch>
                </el-form-item>-->
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">{{ t('cancel') }}</el-button>
        <el-button type="primary" @click="saveEdit()">{{ t('save') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, toRefs, onMounted, watchEffect, watch } from 'vue'
import {
  ElTable,
  ElTableColumn,
  ElPagination,
  ElLoading,
  ElTag,
  ElButton, ElMessage
} from 'element-plus'
import { useRouter } from 'vue-router'
import useRepaySchemeStore from '@/stores/repaySchemeStore'
import { getProductConfigById, changeProductStatus, saveProductConfig } from '@/api/product'
import { storeToRefs } from 'pinia'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

const repaySchemeStore = useRepaySchemeStore()
const router = useRouter()
const centerDialogVisible = ref(false)
const editDialogVisible = ref(false)
const loadingData = ref(false)
const configList = ref([])

const loadData = () => {
  if (!formInline.product_id) {
    return
  }
  loadingData.value = true
  getProductConfigById(formInline.product_id)
    .then((res) => {
      if (res && res.id) {
        configList.value = []
        configList.value.push(res)
      }
    })
    .catch((err) => {
      console.log('getProductConfigById err:', err)
    }).finally(() => {
    loadingData.value = false
  })
}

onMounted(() => {
  repaySchemeStore.getProductList()
  loadData()
})

const { productList } = storeToRefs(repaySchemeStore)

const formInline = reactive({
  product_id: null
})

watch(() => productList.value, (newProductList, oldProductList) => {
  if (newProductList.length > 0) {
    formInline.product_id = newProductList[0].product_id
    loadData()
  }
}, { immediate: true })

const state = ref({
  currentPage: 1,
  pageSize: 10
})

const paginatedData = computed(() => {
  if (configList) {
    const start = (state.value.currentPage - 1) * state.value.pageSize
    const end = start + state.value.pageSize
    return configList.value.slice(start, end)
  }
})

const handleQuery = () => {
  loadData()
}

// 存储当前编辑行的数据
const currentRow = ref({})
const handleEdit = (row: any) => {
// 处理编辑逻辑
  console.log('Edit:', row.id)
  currentRow.value = row
  editDialogVisible.value = true
}

// 启用停用文案描述
let enableStatusDesc = ''
let selectItem = {}
// 处理启用/停用逻辑
const handleEnable = (row: any, status: number) => {
  enableStatusDesc = status === 0 ? t('close') : t('open')
  selectItem = row
  centerDialogVisible.value = true
}

const doChangeProductStatus = () => {
  changeProductStatus(selectItem.product_id, selectItem.apply_switch === 1 ? 0 : 1)
    .then((res) => {
      console.log('changeProductStatus res:', res)
      loadData()
      centerDialogVisible.value = false
    })
    .catch((err) => {
      console.log('changeProductStatus err:', err)
    })
}

const saveEdit = () => {
  if (currentRow.value.apply_end_time <= currentRow.value.apply_start_time) {
    ElMessage.error(t('endTimeMustLaterThanStartTime'))
    return
  }
  saveProductConfig(currentRow.value)
    .then((res) => {
      console.log('saveProductConfig res:', res)
      loadData()
      editDialogVisible.value = false
    })
    .catch((err) => {
      console.log('saveProductConfig err:', err)
    })
}


const handleSizeChange = (newSize: any) => {
  state.value.pageSize = newSize
}

const handleCurrentChange = (newPage: any) => {
  state.value.currentPage = newPage
}

// 导出响应式状态的引用
const { currentPage, pageSize } = toRefs(state.value)
</script>

<style scoped lang="scss">
.top {
  width: 98%;
  margin-top: 28px;
  margin-bottom: 10px;

  .add {
    float: right;
  }

  .status {
    width: 180px;
  }
}

.table_content {
  width: 98%;
  margin-top: 20px;
}
</style>
